package com.mmc.sqlSession.xml;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mmc.container.Configration;
import com.mmc.container.MappedStatement;
import com.mmc.utils.Resources;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class XmlConfigerBuilder {

    public static Configration parseConfiguration(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {
        Document document=new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        List<Element> propertyElements = rootElement.selectNodes("property");
        Properties properties=new Properties();
        for (Element element:propertyElements){
            String name = element.attributeValue("name");
            String value = element.attributeValue("value");
            properties.setProperty(name,value);
        }

        //连接池
        ComboPooledDataSource comboPooledDataSource = new
                ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("user"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));

        //mapper部分
        List<Element> list = rootElement.selectNodes("//mapper");

        Configration configration=new Configration();
        configration.setDataSource(comboPooledDataSource);
        for (Element element:list){
            String mapperResource = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsSteam(mapperResource);
            Map<String, MappedStatement> mappedStatementMap = XmlMapperBuilder.parse(resourceAsSteam);
            configration.getStatementMap().putAll(mappedStatementMap);
        }
        return configration;
    }
}
